﻿using System;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
using VisualSearch.Core;

namespace VisualSearch.Core
{
    public class SearchHandler : System.Web.IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            var query = context.Request.QueryString["q"];
            if (!string.IsNullOrEmpty(query))
            {
                context.Response.ContentType = "application/xml";
                context.Response.Write(Search(context, query));
                //context.Response.Flush();
            }
        }
        #endregion
        private static string Search(System.Web.HttpContext context, string keyword)
        {
            var provider = SearchFactory.CreateProvider();
            provider.PhotoUrl = String.Format("{0}//{1}{2}", context.Request.Url.Scheme, context.Request.Url.Host, System.Web.VirtualPathUtility.ToAbsolute("~/Photo"));
            var searchResult = provider.Search(keyword);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(SearchSuggestion));
            using (var memoryStream = new MemoryStream())
            {
                var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xmlSerializer.Serialize(xmlTextWriter, searchResult);
                return memoryStream.ToUTF8String();
            }
        }
        private static byte[] GetPhotoStream(string Id)
        {
            var provider = SearchFactory.CreateProvider();
            var photo = provider.GetPhotoStream(Id);
            return photo;
        }
    }
}
